package com.kfm.listener;

import com.kfm.util.Contains;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Map;

@WebListener
public class MySessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();

        // 存 在线用户的容器
        Object attribute = servletContext.getAttribute(Contains.ONLINE_ACCOUNT);

        if (attribute instanceof Map map) {
            // 用 session id 作为 key  session对象作为 value
            map.put(session.getId(), session);
        }
    }


    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext servletContext = session.getServletContext();

        // 存 在线用户的容器
        Object attribute = servletContext.getAttribute(Contains.ONLINE_ACCOUNT);

        if (attribute instanceof Map map) {
            map.remove(session.getId());
        }
    }
}
